import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuthStore } from '../store/auth';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('../components/helloPage.vue'),
          meta: {
            index: 1,
          }
        },

        {
          path: '/about',
          name: 'about',
          component: () => import('../components/aboutView.vue'),
          meta: {
            index: 2,
          }
        },

        {
          path: '/sch',
          name: 'sch',
          component: () => import('../components/myEdu.vue'),
          meta: {
            index: 3,
          }
        },

        {
          path: '/login',
          name: 'Login',
          component: () => import('../components/LoginForm.vue')
        },
      ],
      redirect: '/welcome',
    },

    {
      path: '/auth',
      name: 'Auth',
      component: () => import('../views/authView.vue'),
      // 添加路由匹配限制
      beforeEnter: (to, from, next) => {
        if (to.path === '/auth') next();
        else next(false); // 阻止非精确匹配的路由
      }
    },
  ],
});

router.beforeEach(async (to) => {
  const authStore = useAuthStore();
  
  try {
    if (authStore.token && !authStore.userInfo) {
      await authStore.fetchUserInfo();
      
      // 添加默认头像处理
      if (!authStore.userInfo?.avatar) {
        authStore.userInfo.avatar = '/default-avatar.png';
      }
    }
  } catch (error) {
    console.error('用户信息获取失败:', error);
    authStore.logout();
  }
});

export default router
